const mongo = require('../db/mongo') // mongo
const { ObjectID } = require('mongodb')
const COLLECTION = 'articles' // collection

/**
 * 获取博客列表
 * @param {object} options
 */
const getList = async (options) => {
  let author, result
  const {pageSize, currentPage, meta} = options
  meta.method === 'POST' ? author = { author: meta.author } : author = {}
  const skipNum = (currentPage - 1) * pageSize, limitNum = parseInt(pageSize)

  let dbo = await mongo()
  if (Number.isInteger(pageSize)) {
    // 聚合
    result = await dbo.collection(COLLECTION).aggregate([
      { $lookup: { from: 'user', localField: 'author', foreignField: 'username', as: 'nickname'} },
      { $sort:{ createTime: -1 } },
      { $skip: skipNum },
      { $limit:  limitNum }
    ]).toArray()
  } else {
    result = await dbo.collection(COLLECTION).aggregate([
      { $lookup: { from: 'user', localField: 'author', foreignField: 'username', as:'nickname'} },
      { $sort: { createTime: -1 } }
    ]).toArray()
  }
  result.forEach((d) => {
    d.nickname = d.nickname[0].nickname
    delete d.author
  })
  return result
}

/**
 * 获取博客详情
 * @param {string} query 
 */
const getDetail = async (query) => {
  let _id = ObjectID(query._id), result
  let dbo = await mongo()
  result = await dbo.collection(COLLECTION).aggregate([
    { $lookup: { from: 'user', localField: 'author', foreignField: 'username', as:'nickname'} },
    { $match: { _id } }
  ]).toArray()
  result[0].nickname = result[0].nickname[0].nickname
  delete result[0].author
  return result[0]
}

/**
 * 发布博客
 * @param {object} article 
 * @param {string} author 
 */
const publish = async (article, username) => {
  Object.assign(article, {
    createTime: Date.now(),
    editTime: Date.now(),
    isTop: 0,
    author: username
  })
  let dbo = await mongo()
  return await dbo.collection(COLLECTION).insertOne(article)
}

/**
 * 更新博客
 * @param {object} article 
 */
const update = async (article) => {
  if (article._id) article._id = ObjectID(article._id)
  let dbo = await mongo()
  return await dbo.collection(COLLECTION).updateOne({_id: article._id}, {
    $set: article
  })
}

/**
 * 删除博客
 * @param {object} article 
 */
const del = async (article) => {
  if (article._id) article._id = ObjectID(article._id)
  let dbo = await mongo()
  return await dbo.collection(COLLECTION).remove(article)
}

// 获取博客数量
const getCount = async () => {
  let dbo = await mongo()
  let { count } = await dbo.collection(COLLECTION).stats()
  return count
}

module.exports = {
  getList,
  getDetail,
  publish,
  update,
  del,
  getCount
}
